import { createRouter, createWebHistory } from 'vue-router';
import Login from '@/views/login/login.vue';
import Regist from '@/views/regist/regist.vue';

import Table from '@/views/table/table.vue';
import Home from '@/views/home/home.vue';
import Forget from '@/views/forget/forget.vue';


const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home,
        redirect: "/login",
        children: [
            // 添加子路由
            {
                path: '/login',
                name: 'login',
                component: Login,

            },
            {
                path: '/regist',
                name: 'regist',
                component: Regist,
            }, {
                path: "/forget",
                name: 'forget',
                component: Forget
            }
        ],
    }, {
        path: '/table',
        name: 'table',
        component: Table,
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

// 检查token是否过期的函数
function isTokenExpired() {
    // 这里你可以根据实际情况编写检查token过期的逻辑
    // 例如，从localStorage或cookie中获取token，然后解析并检查其有效期
    const token = localStorage.getItem('token');
    if (!token) {
        return true;
    }
    // 假设token是一个包含exp属性的对象，表示过期时间
    const decodedToken = JSON.parse(atob(token.split('.')[1]));
    console.log(decodedToken);
    const currentTime = new Date().getTime() / 1000;

    return decodedToken.exp < currentTime;
}

// 路由守卫
router.beforeEach((to, from, next) => {
    if (to.path === '/login' && isTokenExpired() || to.path == "/regist" || to.path == "/forget") {
        // 如果当前在login页面且token已过期，则允许访问
        next();
    } else if (to.path === '/login' && !isTokenExpired()) {
        // 如果当前在login页面且token未过期，则重定向到其他页面，例如首页
        next('/table');
    } else {
        // 对于其他页面，检查token是否过期
        if (isTokenExpired()) {
            // 如果token过期，重定向到登录页面
            next('/login');
        } else {
            // 如果token未过期，允许访问
            next();
        }
    }
});


export default router;